const crypto = require("crypto");
const managerUser = require("../model/mangerUser");

const Jwt = require("../untils/jwt");

/**
 * @api {get}  统一返回示例说明
 * @apiName 返回说明
 * @apiGroup 0返回说明
 * @apiVersion  1.0.0
 
 * @apiSuccess (200) {type} code 0 成功 1 失败
 * @apiSuccess (200) {type} message 信息
 * @apiSuccess (200) {type} data 数据
 *
 * @apiSuccessExample {type} 返回示例:
 * {
    code: 0,
    message: "管理员登录成功",
    data: {
      type: type,
      currentAuthority: "admin",
      user: "admin",
      token: ’sawfawfawfawfawfawgsv‘,
    },
 * }
 */
const fn_init = async () => {
  const userinfo = await managerUser.findOne({ userName: "admin" });
  if (userinfo === null) {
    const createdAdmin = await managerUser.create({
      phone: 0,
      userName: "admin",
      password: "admin",
      currentAuthority: "admin",
    });
    console.log(createdAdmin);
  }
};
// fn_init();

const fn_register = async (ctx) => {
  //后台管理系统注册
  const {
    userName,
    email,
    password,
    avatar,
    role_id,
    phone,
    currentAuthority,
  } = ctx.request.body;
  const userNameRes = await managerUser.findOne({ userName });
  const emailRes = await managerUser.findOne({ email });
  const phoneRes = await managerUser.findOne({ phone });
  if (userNameRes === null && emailRes === null && phoneRes === null) {
    const hash = crypto.createHash("md5");
    hash.update(password);
    let signPassWord = hash.digest(`hex`);
    const createUser = await managerUser.create({
      userName,
      email,
      password: signPassWord,
      role_id,
      phone,
      avatar,
      currentAuthority,
    });
    if (createUser !== null) {
      ctx.body = {
        code: 0,
        message: "创建成功",
        data: createUser,
      };
    }
  }
};

/**
 * @api {post} /login 用户登录接口
 * @apiName 用户登录接口
 * @apiGroup 登录
 * @apiVersion  1.0.0
 * 
 * @apiParam {String} userName 用户名
 * @apiParam {String} password 密码
 * 
 * @apiSuccess (200) {string} type 
 * @apiSuccess (200) {string} currentAuthority 当前权限角色
 * @apiSuccess (200) {string} user 用户名
 * @apiSuccess (200) {string} token token
 * 
 * @apiParamExample  {type} 请求示例:
  {
    userName : 'admin',
    password:'sss'
  }
 * 
 * 
 * @apiSuccessExample {type} 返回示例:
 * {
    code: 0,
    message: "管理员登录成功",
    data: {
      type: type,
      currentAuthority: "admin",
      user: "admin",
      token: ’sawfawfawfawfawfawgsv‘,
    },
 * }
 */
const fn_login = async (ctx, next) => {
  try {
    const { userName, password, type } = ctx.request.body;
    const hash = crypto.createHash("md5");
    hash.update(password);
    let signPassWord = hash.digest(`hex`);
    console.log(signPassWord.toString());
    if (userName === "admin" && password === "admin") {
      const jwt = new Jwt({ userName });
      ctx.body = {
        code: 0,
        message: "管理员登录成功",
        data: {
          type: type,
          currentAuthority: "admin",
          user: "admin",
          id: '0',
          // 生成 token 返回给客户端
          token: jwt.generateToken(),
        },
      };
    } else {
      const res = await managerUser.findOne({ userName, password });
      if (res !== null) {
        const jwt = new Jwt({ userName, id: res._id });
        ctx.body = {
          code: 0,
          message: "登录成功",
          data: {
            type: type,
            currentAuthority: res.currentAuthority,
            user: res.userName,
            id: res._id,
            // 生成 token 返回给客户端
            token: jwt.generateToken(),
          },
        };
      } else {
        ctx.body = {
          code: -1,
          data: null,
          message: "用户名或密码错误",
        };
      }
    }
  } catch (error) {
    ctx.body = {
      code: -1,
      message: "登录失败：" + error,
      data: null,
    };
  }
};

module.exports = {
  "POST /login": fn_login,
  "POST /register": fn_register,
};
